package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Student;
import com.example.mapper.StudentMapper;
import com.example.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    
    @Override
    public Student getByStudentNo(String studentNo) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getStudentNo, studentNo);
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePhysicalExamData(Long id, String physicalExamData) {
        Student student = getById(id);
        if (student == null) {
            return false;
        }
        student.setPhysicalExamData(physicalExamData);
        return updateById(student);
    }

    @Override
    public Student getByIpAddress(String ipAddress) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getIpAddress, ipAddress);
        return getOne(wrapper);
    }

    @Override
    public void importStudentsFromExcel(Long schoolId, MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }

        log.info("开始处理文件: {}, 大小: {} bytes", file.getOriginalFilename(), file.getSize());

        List<Student> students = new ArrayList<>();
        int rowCount = 0;

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            // 跳过表头
            String header = reader.readLine();
            if (header == null) {
                throw new RuntimeException("文件内容为空");
            }
            log.debug("表头: {}", header);

            String line;
            while ((line = reader.readLine()) != null) {
                rowCount++;
                try {
                    log.debug("处理第 {} 行数据: {}", rowCount, line);
                    
                    // 使用更可靠的方式解析 CSV 数据
                    List<String> fields = new ArrayList<>();
                    StringBuilder currentField = new StringBuilder();
                    boolean inQuotes = false;
                    boolean inJson = false;
                    
                    for (int i = 0; i < line.length(); i++) {
                        char c = line.charAt(i);
                        if (c == ',' && !inQuotes && !inJson) {
                            fields.add(currentField.toString().trim());
                            currentField = new StringBuilder();
                        } else if (c == '"') {
                            inQuotes = !inQuotes;
                        } else if (c == '{' && !inQuotes) {
                            inJson = true;
                            currentField.append(c);
                        } else if (c == '}' && !inQuotes) {
                            inJson = false;
                            currentField.append(c);
                        } else {
                            currentField.append(c);
                        }
                    }
                    fields.add(currentField.toString().trim());
                    
                    if (fields.size() < 4) {
                        throw new RuntimeException("数据格式错误，每行应该有4个字段");
                    }

                    Student student = new Student();
                    student.setSchoolId(schoolId);
                    student.setStudentNo(fields.get(0));
                    student.setName(fields.get(1));
                    student.setGender(getGenderValue(fields.get(2)));
                    
                    // 处理体检数据
                    String physicalExamData = fields.get(3);
                    if (physicalExamData != null && !physicalExamData.isEmpty()) {
                        // 确保是有效的JSON格式
                        if (!physicalExamData.startsWith("{")) {
                            physicalExamData = "{" + physicalExamData;
                        }
                        if (!physicalExamData.endsWith("}")) {
                            physicalExamData = physicalExamData + "}";
                        }
                        // 验证JSON格式
                        try {
                            // 这里可以添加JSON格式验证
                            // 如果JSON格式不正确，会抛出异常
                            student.setPhysicalExamData(physicalExamData);
                        } catch (Exception e) {
                            log.error("JSON格式错误: {}", physicalExamData);
                            throw new RuntimeException("体检数据格式错误: " + e.getMessage());
                        }
                    }
                    
                    // 设置默认值
                    student.setDeleted(0);
                    
                    log.debug("解析后的学生数据: {}", student);
                    students.add(student);
                } catch (Exception e) {
                    log.error("处理第 {} 行数据时出错: {}", rowCount, e.getMessage());
                    throw new RuntimeException("处理第 " + rowCount + " 行数据时出错: " + e.getMessage());
                }
            }

            if (students.isEmpty()) {
                throw new RuntimeException("文件中没有有效的数据行");
            }

            log.info("成功解析 {} 条学生数据，准备保存到数据库", students.size());
            
            // 批量保存学生数据
            saveBatch(students);
            
            log.info("学生数据导入完成");
        } catch (IOException e) {
            log.error("文件处理失败: {}", e.getMessage(), e);
            throw new RuntimeException("文件处理失败: " + e.getMessage());
        }
    }

    private Integer getGenderValue(String gender) {
        if (gender == null) return null;
        return gender.contains("男") ? 1 : 0;
    }
} 